package com.ruoyi.car.api;

import com.ruoyi.car.api.bo.*;
import com.ruoyi.car.api.vo.*;
import com.ruoyi.car.domain.*;
import com.ruoyi.car.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 微信业务相关接口
 */
@RestController
@RequestMapping("/wx/biz")
public class WxBizApiController extends BaseController {
    @Autowired
    private ICarInsuranceService insuranceService;

    @Autowired
    private ICarLoanService loanService;

    @Autowired
    private ICarOrderService carOrderService;

    @Autowired
    private ICarTestDriveService carTestDriveService;
    @Autowired
    private ICarGoodsService carGoodsService;
    @Autowired
    private ICarTypeService carTypeService;
    @Autowired
    private ICarCommunityService carCommunityService;
    @Autowired
    private ICarCommunityReplyService carCommunityReplyService;

    @Autowired
    private FormatService formatService;
    @Autowired
    private SmsService smsService;

    /**
     * 贷款/保险查询
     **/
    @PostMapping(value = "/daibao/get_list")
    public AjaxResult daibao(@RequestBody WxDaiBaoBo wxDaiBaoBo) {
        String type = wxDaiBaoBo.getType();
        List<WxDaiBaoVo> resultList = this.queryByType(type);
        return success(resultList);
    }

    /**
     * 服务记录
     **/
    @PostMapping(value = "/get_order")
    public R<WxOrderDriveVo> orderList() {
        WxOrderDriveVo wxOrderDriveVo = new WxOrderDriveVo();
        //只查当前用户的
        Long userId = getUserId();
        //订单信息需要车型详情
        CarOrder carOrder = new CarOrder();
        carOrder.setWxUserId(userId);
        carOrder.setNeedGoodsInfo(true);

        CarTestDrive carTestDrive = new CarTestDrive();
        carTestDrive.setWxUserId(userId);
        //转换
        List<CarOrder> carOrders = carOrderService.selectCarOrderList(carOrder);
        wxOrderDriveVo.setOrder(this.transOrderVoList(carOrders));
        wxOrderDriveVo.setDry(carTestDriveService.selectCarTestDriveList(carTestDrive));
        return R.ok(wxOrderDriveVo);
    }

    /**
     * 预约试驾
     **/
    @PostMapping(value = "/add_dry")
    public R<Void> addDry(@Validated @RequestBody WxAddDryBo wxAddDryBo) {
        //校验短信验证码
        smsService.checkCode(wxAddDryBo.getPhone(),wxAddDryBo.getCode());
        CarTestDrive carTestDrive = new CarTestDrive();
        BeanUtils.copyProperties(wxAddDryBo, carTestDrive);
        carTestDrive.setWxUserId(getUserId());
        carTestDriveService.insertCarTestDrive(carTestDrive);
        return R.ok(null, "申请中，请等待");
    }

    /**
     * 立即订购
     **/
    @PostMapping(value = "/add_order")
    public R<Void> addOrder(@Validated @RequestBody WxAddOrderBo addOrderBo) {
        CarOrder carOrder = new CarOrder();
        BeanUtils.copyProperties(addOrderBo, carOrder);
        carOrder.setWxUserId(getUserId());
        carOrder.setPayDate(new Date());
        carOrderService.insertCarOrder(carOrder);
        return R.ok(null, "支付成功");
    }

    /**
     * 获取商品
     **/
    @PostMapping(value = "/get_goods")
    public R<List<WxCarGoodsVo>> getGoods(@RequestBody WxGoodsQueryBo wxGoodsQueryBo) {
        CarGoods queryCardGoods = new CarGoods();
        BeanUtils.copyProperties(wxGoodsQueryBo, queryCardGoods);
        List<CarGoods> carGoodsList = carGoodsService.selectCarGoodsList(queryCardGoods);
        List<WxCarGoodsVo> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(carGoodsList)) {
            result = carGoodsList.stream().map(this::transWxCarGoodsVo).collect(Collectors.toList());
        }
        return R.ok(result);
    }

    /**
     * 获取商品类型
     **/
    @PostMapping(value = "/get_type")
    public R<List<WxCarTypeVo>> getType() {
        List<CarType> carTypeList = carTypeService.selectCarTypeList(new CarType());
        List<WxCarTypeVo> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(carTypeList)) {
            result = carTypeList.stream().map(carType -> {
                WxCarTypeVo wxCarTypeVo = new WxCarTypeVo();
                BeanUtils.copyProperties(carType, wxCarTypeVo);
                return wxCarTypeVo;
            }).collect(Collectors.toList());
        }
        return R.ok(result);
    }

    /**
     * 获取社区发帖
     **/
    @PostMapping(value = "/get_asso")
    public R<List<WxCarCommunityVo>> getAsso() {
        CarCommunity carCommunity = new CarCommunity();
        carCommunity.setNeedReply(true);
        List<CarCommunity> carCommunityList = carCommunityService.selectCarCommunityList(carCommunity);
        if (CollectionUtils.isEmpty(carCommunityList)) {
            return R.ok(new ArrayList<>());
        }
        List<WxCarCommunityVo> wxCarCommunityVoList = new ArrayList<>();
        for (CarCommunity community : carCommunityList) {
            WxCarCommunityVo vo = new WxCarCommunityVo();
            BeanUtils.copyProperties(community, vo);
            //将图片地址替换
            vo.setImgs(transImgArray(community.getImgs()));
            vo.setAvatarUrl(formatService.replaceDomainName(vo.getAvatarUrl()));
            //将回复里的图片地址也替换掉
            List<CarCommunityReply> replyList = vo.getReplyList();
            if (CollectionUtils.isNotEmpty(replyList)) {
                for (CarCommunityReply reply : replyList) {
                    reply.setAvatarUrl(formatService.replaceDomainName(reply.getAvatarUrl()));
                }
            }
            wxCarCommunityVoList.add(vo);
        }
        return R.ok(wxCarCommunityVoList);
    }

    /**
     * 社区发帖
     **/
    @PostMapping(value = "/push_asso")
    public R<Void> pushAsso(@RequestBody WxPushAssoBo wxPushAssoBo) {
        CarCommunity carCommunity = new CarCommunity();
        BeanUtils.copyProperties(wxPushAssoBo, carCommunity);
        carCommunity.setWxUserId(getUserId());
        carCommunityService.insertCarCommunity(carCommunity);
        return R.ok();
    }

    /**
     * 发送回复
     **/
    @PostMapping(value = "/push_reply")
    public R<Void> pushAsso(@RequestBody WxPushReplyBo wxPushReplyBo) {
        CarCommunityReply reply = new CarCommunityReply();
        BeanUtils.copyProperties(wxPushReplyBo, reply);
        reply.setWxUserId(getUserId());
        carCommunityReplyService.insertCarCommunityReply(reply);
        return R.ok();
    }


    private List<WxDaiBaoVo> queryByType(String type) {
        List<WxDaiBaoVo> resultList = new ArrayList<>();
        //查询贷款列表
        if (Objects.equals(type, "dai")) {
            List<CarLoan> carLoans = loanService.selectCarLoanList(new CarLoan());
            if (CollectionUtils.isEmpty(carLoans)) {
                return resultList;
            }
            for (CarLoan carLoan : carLoans) {
                WxDaiBaoVo wxDaiBaoVo = new WxDaiBaoVo();
                BeanUtils.copyProperties(carLoan, wxDaiBaoVo);
                wxDaiBaoVo.setImg(formatService.replaceDomainName(wxDaiBaoVo.getImg()));
                resultList.add(wxDaiBaoVo);
            }

        } else {
            //查询保险列表
            List<CarInsurance> carInsurances = insuranceService.selectCarInsuranceList(new CarInsurance());
            if (CollectionUtils.isEmpty(carInsurances)) {
                return resultList;
            }
            for (CarInsurance carInsurance : carInsurances) {
                WxDaiBaoVo wxDaiBaoVo = new WxDaiBaoVo();
                BeanUtils.copyProperties(carInsurance, wxDaiBaoVo);
                wxDaiBaoVo.setImg(formatService.replaceDomainName(wxDaiBaoVo.getImg()));
                resultList.add(wxDaiBaoVo);
            }
        }
        return resultList;
    }

    private WxCarGoodsVo transWxCarGoodsVo(CarGoods carGoods) {
        if (carGoods == null) {
            return null;
        }
        WxCarGoodsVo wxCarGoodsVo = new WxCarGoodsVo();
        BeanUtils.copyProperties(carGoods, wxCarGoodsVo);
        wxCarGoodsVo.setGoodsImgs(transImgArray(carGoods.getGoodsImgs()));
        return wxCarGoodsVo;
    }

    private List<String> transImgArray(String imgs) {
        if (StringUtils.isEmpty(imgs)) {
            return new ArrayList<>();
        }
        List<String> result = new ArrayList<>();
        String[] split = imgs.split(",");
        for (String s : split) {
            //替换域名
            s = formatService.replaceDomainName(s);
            result.add(s);
        }
        return result;
    }


    public List<WxCarOrderVo> transOrderVoList(List<CarOrder> carOrderList) {
        if (CollectionUtils.isEmpty(carOrderList)) {
            return new ArrayList<>();
        }
        List<WxCarOrderVo> orderVoList = new ArrayList<>();
        for (CarOrder carOrder : carOrderList) {
            WxCarOrderVo wxCarOrderVo = new WxCarOrderVo();
            BeanUtils.copyProperties(carOrder, wxCarOrderVo);
            wxCarOrderVo.setGoods(this.transWxCarGoodsVo(carOrder.getGoods()));
            wxCarOrderVo.setZheng(formatService.replaceDomainName(wxCarOrderVo.getZheng()));
            wxCarOrderVo.setWater(formatService.replaceDomainName(wxCarOrderVo.getWater()));
            wxCarOrderVo.setHun(formatService.replaceDomainName(wxCarOrderVo.getHun()));
            wxCarOrderVo.setCardFront(formatService.replaceDomainName(wxCarOrderVo.getCardFront()));
            wxCarOrderVo.setCardBack(formatService.replaceDomainName(wxCarOrderVo.getCardBack()));
            orderVoList.add(wxCarOrderVo);
        }
        return orderVoList;
    }

}
